package com.lee.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * GroupChatServer
 * 群聊服务
 *
 * @author dralee
 * @date 2021-12-30 23:15:43
 **/
public class GroupChatServer {

    // 定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    // 构造器


    public GroupChatServer() {
        try {
            //  得到选择器
            selector = Selector.open();
            // ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            // 设置非阻塞
            listenChannel.configureBlocking(false);
            // 绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            // 将listenChannel注册到Selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 监听
    public void listen() {
        System.out.println("服务器监听客户端线程：" + Thread.currentThread().getName());
        try {
            // 循环处理
            while (true) {
                int count = selector.select();
                if (count > 0) { // 有事件要处理
                    //  遍历得到selectionKey集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        // 取出selectionKey
                        SelectionKey key = iterator.next();
                        // 监听到accept
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            // 设置非阻塞
                            sc.configureBlocking(false);
                            // 将sc注册到selector
                            sc.register(selector, SelectionKey.OP_READ);
                            System.out.println(sc.getRemoteAddress() + "上线");
                        } else if (key.isReadable()) {
                            // 处理读
                            readData(key);
                        }
                        // 当前key移除，防止重复
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待...");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 读到客户端消息
    private void readData(SelectionKey key) {
        // 定义一个SocketChannel
        SocketChannel channel = null;
        try {
            // 取到关联的channel
            channel = (SocketChannel) key.channel();
            // 创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            // 根据count值做处理
            if (count > 0) {
                // 把缓冲区数据转成字符串
                String msg = new String(buffer.array());
                System.out.println("from客户端：" + msg.trim());
                // 向其它客户端转发消息（去掉自己）
                sendInfoToOtherClients(msg, channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线");
                // 取消注册
                key.cancel();
                // 关闭通道
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    // 转发消息给其它客户（通道）
    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中...");
        System.out.println("服务器转发数据给客户端线程：" + Thread.currentThread().getName());
        // 遍历所有注册到selector上的SocketChannel并排除self
        for (SelectionKey key : selector.keys()) {
            // 通过key取出对应SocketChannel
            Channel targetChannel = key.channel();
            // 排序自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                SocketChannel dest = (SocketChannel) targetChannel;
                // 将msg存到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
                // 将buffer数据写入到通道
                dest.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
        // 创建服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
